package com.zjmcollege.hotpot.controller;

import com.zjmcollege.hotpot.component.FileHandler;
import com.zjmcollege.hotpot.entity.InterviewCase;
import com.zjmcollege.hotpot.enums.FileType;
import com.zjmcollege.hotpot.model.InterviewCaseModel;
import com.zjmcollege.hotpot.model.UploadResultModel;
import com.zjmcollege.hotpot.repository.InterviewCaseRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

import static com.zjmcollege.hotpot.enums.Constants.MD;

/**
 * @author zpym
 * @CopyRight (C) http://www.zjmcollege.com
 * @brief
 * @email 122162005@qq.com
 * @date 2019-11-05 23:27
 */
@Controller
@RequestMapping("/case")
public class InterviewCaseController {
    @Autowired
    private FileHandler fileHandler;

    @Autowired
    private InterviewCaseRepository repository;

    @GetMapping
    public String casePage(Model model) {
        List<InterviewCase> all = repository.findAll();
        for (InterviewCase interviewCase : all) {
            if (interviewCase.getDocType() == MD) {
                // 如果上传的文档类型是 md文档，则将文档替换成 md 文档的具体内容
                interviewCase.setAnswer(fileHandler.
                        getContent(interviewCase.getAnswer(), FileType.MD));
            }
        }

        model.addAttribute("cases", all);
        return "case/list";
    }

    @GetMapping("/add")
    public String addPage() {
        return "case/add";
    }

    @GetMapping("/add/md")
    public String addPageMd() {
        return "case/add-editor-md";
    }

    @PostMapping
    public String add(InterviewCaseModel caseModel) {
        System.out.println(caseModel);
        InterviewCase interviewCase = new InterviewCase();
        BeanUtils.copyProperties(caseModel, interviewCase);
        if (caseModel.getDocType() == MD) {
            UploadResultModel resultMd = fileHandler.
                    upload(caseModel.getAnswer(), FileType.MD);

            interviewCase.setAnswer(resultMd.getUrl());
            interviewCase.setAnswerHtml(null);
        }

        repository.save(interviewCase);

        return "redirect:/case";
    }
}
